package com.loong.musicdemo.adapter;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.loong.musicdemo.R;

import java.util.List;

/**
 * 用于显示历史记录的适配器
 */
public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.ViewHolder> {
    private List<String> histories;//历史记录
    private Handler handler;//用于传输数据

    public SearchHistoryAdapter(List<String> histories, Handler handler) {
        this.histories = histories;
        this.handler = handler;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_history_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String content = histories.get(position);
        holder.history.setText(content);
        holder.root.setOnClickListener(v -> {
            Message msg = Message.obtain();
            msg.what = 2;
            msg.obj = content;
            handler.sendMessage(msg);//发送消息
        });
    }

    @Override
    public int getItemCount() {
        return histories == null ? 0 : histories.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView history;//历史记录显示
        View root;//俯视图

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            root = itemView;
            history = itemView.findViewById(R.id.history);
        }
    }
}